﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Schedule
{
    public delegate void updateDDLHandle();
    class DDLManage
    {
        public DataTable DDLDataTable = new DataTable();
        public List<Deadline> deadlines = Deadline.deadlines;
        public LinkDB link = new LinkDB();
        public static event updateDDLHandle updateDDL = null;

        public DDLManage(string cID)
        {
            DDLDataTable.Columns.Add("任务内容");
            DDLDataTable.Columns.Add("截止日期");
            updateDDLInfo(cID);
        }
       
        public DDLManage() { }
        
        public void dataInit()
        {
            link.getDeadLines();//从数据库读取ddl列表
            updateDDL();
        }

        public bool addDDL(int weekday,int chooseLesson,string task,string deadline)
        {
            
            long courseID=0;
            var query = from c in Course.courses
                        where c.Weekday == weekday && c.BeginLesson <= chooseLesson && (c.LastLesson + c.BeginLesson) > chooseLesson
                        select c;//查出courseID
            try { courseID = ((Course)query.ElementAt(0)).CourseID; }
            catch (Exception)
            {
                return false;
            }
            Deadline newddl = new Deadline(courseID, task, DateTime.Parse(deadline));
            deadlines.Add(newddl);
            link.addDeadline(newddl);//插入数据库
            
            updateDDL();
            return true;
        }

        public void updateDDLInfo(string courseID)
        {
            //更新ddlDataTable
            var query = from ddl in deadlines
                        where ddl.CourseID.ToString() == courseID
                        select ddl;

            foreach (Deadline deadline in query.ToList())
            {
                var values = new object[2];
                values[0] = deadline.Task;
                values[1] = deadline.DeadlineDate.ToShortDateString();
                DDLDataTable.Rows.Add(values);
            }
            
        }

        public void deleteDDL(string courseID,string ddlName)
        {
            link.deleteDeadline(courseID, ddlName);
            DDLDataTable.Clear();
            deadlines.RemoveAll(ddl => ddl.CourseID.ToString() == courseID && ddl.Task == ddlName);
            updateDDLInfo(courseID);
            updateDDL();
        }

        

        public void deleteBycourse(string courseID)
        {
            link.deleteDDLByCourseID(courseID);
            deadlines.RemoveAll(ddl => ddl.CourseID.ToString() == courseID);
            updateDDLInfo(courseID);
            updateDDL();
        }
       
    }
}
